<template>
  <!-- 浮动聊天按钮 -->
  <div 
    v-if="!isOpen"
    class="ai-chat-button"
    :style="buttonStyle"
    @mousedown="startDrag"
    @click="openChat"
    title="凶巴巴"
  >
    <div class="chat-icon">
      <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
        <defs>
          <linearGradient id="bear-float-gradient" x1="0%" y1="0%" x2="0%" y2="100%">
            <stop offset="0%" style="stop-color:#d4a574;stop-opacity:1" />
            <stop offset="100%" style="stop-color:#c89968;stop-opacity:1" />
          </linearGradient>
          <radialGradient id="bear-float-face" cx="50%" cy="50%">
            <stop offset="0%" style="stop-color:#e8c9a0;stop-opacity:1" />
            <stop offset="100%" style="stop-color:#d4a574;stop-opacity:1" />
          </radialGradient>
          <filter id="bear-shadow">
            <feGaussianBlur stdDeviation="3" result="coloredBlur"/>
            <feMerge>
              <feMergeNode in="coloredBlur"/>
              <feMergeNode in="SourceGraphic"/>
            </feMerge>
          </filter>
        </defs>
        
        <!-- 外圈光环 -->
        <circle cx="50" cy="50" r="42" fill="none" stroke="#d4a574" stroke-width="2.5" opacity="0.25">
          <animate attributeName="r" values="42;46;42" dur="3s" repeatCount="indefinite"/>
          <animate attributeName="opacity" values="0.25;0.5;0.25" dur="3s" repeatCount="indefinite"/>
        </circle>
        
        <!-- 左耳 -->
        <circle cx="30" cy="28" r="14" fill="url(#bear-float-gradient)" filter="url(#bear-shadow)"/>
        <circle cx="31" cy="29" r="8" fill="#f5dcc8" opacity="0.9"/>
        
        <!-- 右耳 -->
        <circle cx="70" cy="28" r="14" fill="url(#bear-float-gradient)" filter="url(#bear-shadow)"/>
        <circle cx="69" cy="29" r="8" fill="#f5dcc8" opacity="0.9"/>
        
        <!-- 头部 -->
        <circle cx="50" cy="52" r="32" fill="url(#bear-float-face)" filter="url(#bear-shadow)"/>
        <ellipse cx="50" cy="50" rx="30" ry="31" fill="url(#bear-float-gradient)"/>
        
        <!-- 脸部浅色区域 -->
        <ellipse cx="50" cy="60" rx="20" ry="18" fill="#f5dcc8" opacity="0.9"/>
        
        <!-- 左眼 -->
        <circle cx="38" cy="48" r="5" fill="#2d3436">
          <animate attributeName="r" values="5;4.5;5" dur="2s" repeatCount="indefinite"/>
        </circle>
        <circle cx="39" cy="47" r="2" fill="#ffffff" opacity="0.95"/>
        
        <!-- 右眼 -->
        <circle cx="62" cy="48" r="5" fill="#2d3436">
          <animate attributeName="r" values="5;4.5;5" dur="2s" repeatCount="indefinite"/>
        </circle>
        <circle cx="63" cy="47" r="2" fill="#ffffff" opacity="0.95"/>
        
        <!-- 鼻子 -->
        <ellipse cx="50" cy="60" rx="6" ry="5" fill="#2d3436"/>
        <ellipse cx="49" cy="59" rx="2" ry="1.5" fill="#ffffff" opacity="0.7"/>
        
        <!-- 嘴巴 -->
        <path d="M 50 60 L 50 68" stroke="#2d3436" stroke-width="2.5" stroke-linecap="round"/>
        <path d="M 50 68 Q 44 70 40 68" stroke="#2d3436" stroke-width="2" fill="none" stroke-linecap="round"/>
        <path d="M 50 68 Q 56 70 60 68" stroke="#2d3436" stroke-width="2" fill="none" stroke-linecap="round"/>
        
        <!-- 可爱的腮红 -->
        <ellipse cx="32" cy="58" rx="6" ry="4" fill="#ff9a9e" opacity="0.4">
          <animate attributeName="opacity" values="0.4;0.6;0.4" dur="2s" repeatCount="indefinite"/>
        </ellipse>
        <ellipse cx="68" cy="58" rx="6" ry="4" fill="#ff9a9e" opacity="0.4">
          <animate attributeName="opacity" values="0.4;0.6;0.4" dur="2s" repeatCount="indefinite"/>
        </ellipse>
        
        <!-- AI 小星星装饰 -->
        <circle cx="74" cy="40" r="3.5" fill="#74b9ff" opacity="0.9">
          <animate attributeName="opacity" values="0.9;0.4;0.9" dur="1.5s" repeatCount="indefinite"/>
        </circle>
        <path d="M 74 36 L 74.5 38.5 L 77 39 L 74.5 39.5 L 74 42 L 73.5 39.5 L 71 39 L 73.5 38.5 Z" fill="#ffffff" opacity="0.95">
          <animate attributeName="opacity" values="0.95;0.4;0.95" dur="1.5s" repeatCount="indefinite"/>
        </path>
      </svg>
    </div>
    <div class="chat-badge" v-if="unreadCount > 0">{{ unreadCount }}</div>
  </div>

  <!-- 聊天窗口 -->
  <div 
    v-if="isOpen"
    class="ai-chat-window"
    :style="windowStyle"
  >
    <!-- 标题栏 -->
    <div class="chat-header" @mousedown="startDrag">
      <div class="header-title">
        <div class="avatar-3d">
          <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
            <defs>
              <linearGradient id="bear-gradient" x1="0%" y1="0%" x2="0%" y2="100%">
                <stop offset="0%" style="stop-color:#d4a574;stop-opacity:1" />
                <stop offset="100%" style="stop-color:#c89968;stop-opacity:1" />
              </linearGradient>
              <radialGradient id="bear-face" cx="50%" cy="50%">
                <stop offset="0%" style="stop-color:#e8c9a0;stop-opacity:1" />
                <stop offset="100%" style="stop-color:#d4a574;stop-opacity:1" />
              </radialGradient>
            </defs>
            
            <!-- 左耳 -->
            <circle cx="32" cy="28" r="12" fill="url(#bear-gradient)"/>
            <circle cx="33" cy="29" r="7" fill="#f5dcc8" opacity="0.9"/>
            
            <!-- 右耳 -->
            <circle cx="68" cy="28" r="12" fill="url(#bear-gradient)"/>
            <circle cx="67" cy="29" r="7" fill="#f5dcc8" opacity="0.9"/>
            
            <!-- 头部 -->
            <circle cx="50" cy="50" r="28" fill="url(#bear-face)"/>
            <ellipse cx="50" cy="48" rx="26" ry="27" fill="url(#bear-gradient)"/>
            
            <!-- 脸部浅色区域 -->
            <ellipse cx="50" cy="56" rx="18" ry="16" fill="#f5dcc8" opacity="0.85"/>
            
            <!-- 左眼 -->
            <circle cx="40" cy="46" r="4" fill="#2d3436"/>
            <circle cx="41" cy="45" r="1.5" fill="#ffffff" opacity="0.9"/>
            
            <!-- 右眼 -->
            <circle cx="60" cy="46" r="4" fill="#2d3436"/>
            <circle cx="61" cy="45" r="1.5" fill="#ffffff" opacity="0.9"/>
            
            <!-- 鼻子 -->
            <ellipse cx="50" cy="56" rx="5" ry="4" fill="#2d3436"/>
            <ellipse cx="49" cy="55" rx="1.5" ry="1.2" fill="#ffffff" opacity="0.6"/>
            
            <!-- 嘴巴 -->
            <path d="M 50 56 L 50 62" stroke="#2d3436" stroke-width="2" stroke-linecap="round"/>
            <path d="M 50 62 Q 45 64 42 62" stroke="#2d3436" stroke-width="1.5" fill="none" stroke-linecap="round"/>
            <path d="M 50 62 Q 55 64 58 62" stroke="#2d3436" stroke-width="1.5" fill="none" stroke-linecap="round"/>
            
            <!-- 可爱的腮红 -->
            <ellipse cx="34" cy="54" rx="5" ry="3.5" fill="#ff9a9e" opacity="0.35"/>
            <ellipse cx="66" cy="54" rx="5" ry="3.5" fill="#ff9a9e" opacity="0.35"/>
            
            <!-- AI标记 - 小星星 -->
            <circle cx="72" cy="38" r="3" fill="#74b9ff" opacity="0.85">
              <animate attributeName="opacity" values="0.85;0.4;0.85" dur="2s" repeatCount="indefinite"/>
            </circle>
            <path d="M 72 35 L 72.5 37 L 74.5 37.5 L 72.5 38 L 72 40 L 71.5 38 L 69.5 37.5 L 71.5 37 Z" fill="#ffffff" opacity="0.9">
              <animate attributeName="opacity" values="0.9;0.3;0.9" dur="2s" repeatCount="indefinite"/>
            </path>
          </svg>
        </div>
        <span class="title-text">凶巴巴</span>
        <span class="status-indicator" :class="{ 'online': isConnected, 'offline': !isConnected }">
          {{ isConnected ? '在线' : '' }}
        </span>
      </div>
      <div class="header-actions">
        <button @click="minimizeChat" class="action-btn" title="最小化">−</button>
        <button @click="closeChat" class="action-btn" title="关闭">×</button>
      </div>
    </div>

    <!-- 消息列表 -->
    <div class="chat-messages" ref="messagesContainer">
      <!-- 欢迎消息 -->
      <div v-if="messages.length === 0" class="welcome-message">
        <div class="welcome-icon">👋</div>
        <h3>您好！我是凶巴巴</h3>
        <p>我可以帮您解答关于仓库管理系统的问题</p>
        <div class="quick-questions">
          <button @click="askQuestion('如何查询库存？')" class="quick-btn">如何查询库存？</button>
          <button @click="askQuestion('如何创建入库单？')" class="quick-btn">如何创建入库单？</button>
          <button @click="askQuestion('如何处理订单？')" class="quick-btn">如何处理订单？</button>
        </div>
      </div>

      <!-- 聊天消息 -->
      <div 
        v-for="(msg, index) in messages" 
        :key="index"
        class="message-item"
        :class="[msg.role, detectMessageTypeClass(msg.content)]"
      >
        <div class="message-avatar">
          <span v-if="msg.role === 'user'">👤</span>
          <svg v-else viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" class="bear-avatar">
            <defs>
              <linearGradient id="bear-msg-gradient" x1="0%" y1="0%" x2="0%" y2="100%">
                <stop offset="0%" style="stop-color:#d4a574;stop-opacity:1" />
                <stop offset="100%" style="stop-color:#c89968;stop-opacity:1" />
              </linearGradient>
              <radialGradient id="bear-msg-face" cx="50%" cy="50%">
                <stop offset="0%" style="stop-color:#e8c9a0;stop-opacity:1" />
                <stop offset="100%" style="stop-color:#d4a574;stop-opacity:1" />
              </radialGradient>
            </defs>
            
            <!-- 左耳 -->
            <circle cx="28" cy="25" r="13" fill="url(#bear-msg-gradient)"/>
            <circle cx="29" cy="26" r="7" fill="#f5dcc8"/>
            
            <!-- 右耳 -->
            <circle cx="72" cy="25" r="13" fill="url(#bear-msg-gradient)"/>
            <circle cx="71" cy="26" r="7" fill="#f5dcc8"/>
            
            <!-- 头部 -->
            <circle cx="50" cy="52" r="30" fill="url(#bear-msg-face)"/>
            <ellipse cx="50" cy="50" rx="28" ry="29" fill="url(#bear-msg-gradient)"/>
            
            <!-- 脸部浅色区域 -->
            <ellipse cx="50" cy="58" rx="19" ry="17" fill="#f5dcc8"/>
            
            <!-- 左眼 -->
            <circle cx="38" cy="46" r="4.5" fill="#2d3436"/>
            <circle cx="39" cy="45" r="1.8" fill="#ffffff"/>
            
            <!-- 右眼 -->
            <circle cx="62" cy="46" r="4.5" fill="#2d3436"/>
            <circle cx="63" cy="45" r="1.8" fill="#ffffff"/>
            
            <!-- 鼻子 -->
            <ellipse cx="50" cy="58" rx="5.5" ry="4.5" fill="#2d3436"/>
            <ellipse cx="49" cy="57" rx="1.8" ry="1.3" fill="#ffffff" opacity="0.7"/>
            
            <!-- 嘴巴 -->
            <path d="M 50 58 L 50 65" stroke="#2d3436" stroke-width="2.2" stroke-linecap="round"/>
            <path d="M 50 65 Q 44 67 41 65" stroke="#2d3436" stroke-width="1.8" fill="none" stroke-linecap="round"/>
            <path d="M 50 65 Q 56 67 59 65" stroke="#2d3436" stroke-width="1.8" fill="none" stroke-linecap="round"/>
            
            <!-- 可爱的腮红 -->
            <ellipse cx="32" cy="56" rx="5.5" ry="3.5" fill="#ff9a9e" opacity="0.4"/>
            <ellipse cx="68" cy="56" rx="5.5" ry="3.5" fill="#ff9a9e" opacity="0.4"/>
          </svg>
        </div>
        <div class="message-content">
          <div class="message-text" v-html="formatMessage(msg.content)"></div>
          <div class="message-time">{{ formatTime(msg.timestamp) }}</div>
        </div>
      </div>

      <!-- 加载中 -->
      <div v-if="isLoading" class="message-item assistant">
        <div class="message-avatar">
          <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" class="bear-avatar">
            <defs>
              <linearGradient id="bear-loading-gradient" x1="0%" y1="0%" x2="0%" y2="100%">
                <stop offset="0%" style="stop-color:#d4a574;stop-opacity:1" />
                <stop offset="100%" style="stop-color:#c89968;stop-opacity:1" />
              </linearGradient>
              <radialGradient id="bear-loading-face" cx="50%" cy="50%">
                <stop offset="0%" style="stop-color:#e8c9a0;stop-opacity:1" />
                <stop offset="100%" style="stop-color:#d4a574;stop-opacity:1" />
              </radialGradient>
            </defs>
            
            <!-- 左耳 -->
            <circle cx="28" cy="25" r="13" fill="url(#bear-loading-gradient)"/>
            <circle cx="29" cy="26" r="7" fill="#f5dcc8"/>
            
            <!-- 右耳 -->
            <circle cx="72" cy="25" r="13" fill="url(#bear-loading-gradient)"/>
            <circle cx="71" cy="26" r="7" fill="#f5dcc8"/>
            
            <!-- 头部 -->
            <circle cx="50" cy="52" r="30" fill="url(#bear-loading-face)"/>
            <ellipse cx="50" cy="50" rx="28" ry="29" fill="url(#bear-loading-gradient)"/>
            
            <!-- 脸部浅色区域 -->
            <ellipse cx="50" cy="58" rx="19" ry="17" fill="#f5dcc8"/>
            
            <!-- 左眼 -->
            <circle cx="38" cy="46" r="4.5" fill="#2d3436"/>
            <circle cx="39" cy="45" r="1.8" fill="#ffffff"/>
            
            <!-- 右眼 -->
            <circle cx="62" cy="46" r="4.5" fill="#2d3436"/>
            <circle cx="63" cy="45" r="1.8" fill="#ffffff"/>
            
            <!-- 鼻子 -->
            <ellipse cx="50" cy="58" rx="5.5" ry="4.5" fill="#2d3436"/>
            <ellipse cx="49" cy="57" rx="1.8" ry="1.3" fill="#ffffff" opacity="0.7"/>
            
            <!-- 嘴巴 -->
            <path d="M 50 58 L 50 65" stroke="#2d3436" stroke-width="2.2" stroke-linecap="round"/>
            <path d="M 50 65 Q 44 67 41 65" stroke="#2d3436" stroke-width="1.8" fill="none" stroke-linecap="round"/>
            <path d="M 50 65 Q 56 67 59 65" stroke="#2d3436" stroke-width="1.8" fill="none" stroke-linecap="round"/>
            
            <!-- 可爱的腮红 -->
            <ellipse cx="32" cy="56" rx="5.5" ry="3.5" fill="#ff9a9e" opacity="0.4"/>
            <ellipse cx="68" cy="56" rx="5.5" ry="3.5" fill="#ff9a9e" opacity="0.4"/>
          </svg>
        </div>
        <div class="message-content">
          <div class="typing-indicator">
            <span></span><span></span><span></span>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入框 -->
    <div class="chat-input">
      <el-input
        v-model="inputMessage"
        type="textarea"
        :rows="2"
        placeholder="输入您的问题..."
        @keydown.enter.prevent="handleEnter"
        :disabled="isLoading"
      />
      <button 
        @click="sendMessage" 
        class="send-btn"
        :disabled="!inputMessage.trim() || isLoading"
      >
        {{ isLoading ? '⏳' : '📤' }}
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, nextTick, onMounted, onUnmounted, getCurrentInstance } from 'vue';
import { sendRagflowChatStream, checkRagflowHealth } from '@/api/ragflowAI.js';

const { proxy } = getCurrentInstance();

// 状态管理
const isOpen = ref(false);
const isConnected = ref(true);
const isLoading = ref(false);
const inputMessage = ref('');
const messages = ref([]);
const unreadCount = ref(0);

// 拖拽相关
const position = reactive({
  x: window.innerWidth - 400,
  y: window.innerHeight - 600
});

const isDragging = ref(false);
const dragStart = reactive({ x: 0, y: 0 });

// 样式计算
const buttonStyle = computed(() => ({
  right: `${window.innerWidth - position.x - 60}px`,
  bottom: `${window.innerHeight - position.y - 60}px`
}));

const windowStyle = computed(() => ({
  left: `${position.x}px`,
  top: `${position.y}px`
}));

// 消息容器引用
const messagesContainer = ref(null);

const openChat = () => {
  isOpen.value = true;
  unreadCount.value = 0;
  nextTick(() => scrollToBottom());
};

const closeChat = () => {
  isOpen.value = false;
};

const minimizeChat = () => {
  isOpen.value = false;
};

const startDrag = (e) => {
  if (e.target.closest('.action-btn')) return;
  isDragging.value = true;
  dragStart.x = e.clientX - position.x;
  dragStart.y = e.clientY - position.y;
  document.addEventListener('mousemove', onDrag);
  document.addEventListener('mouseup', stopDrag);
  e.preventDefault();
};

const onDrag = (e) => {
  if (!isDragging.value) return;
  let newX = e.clientX - dragStart.x;
  let newY = e.clientY - dragStart.y;
  const maxX = window.innerWidth - (isOpen.value ? 400 : 60);
  const maxY = window.innerHeight - (isOpen.value ? 600 : 60);
  newX = Math.max(0, Math.min(newX, maxX));
  newY = Math.max(0, Math.min(newY, maxY));
  position.x = newX;
  position.y = newY;
};

const stopDrag = () => {
  isDragging.value = false;
  document.removeEventListener('mousemove', onDrag);
  document.removeEventListener('mouseup', stopDrag);
};

const sendMessage = async () => {
  const message = inputMessage.value.trim();
  if (!message || isLoading.value) return;
  
  // 添加用户消息
  messages.value.push({
    role: 'user',
    content: message,
    timestamp: new Date()
  });
  
  inputMessage.value = '';
  isLoading.value = true;
  nextTick(() => scrollToBottom());
  
  try {
    // 构建历史记录（最多保留最近10条）
    const history = messages.value.slice(-11, -1).map(msg => ({
      role: msg.role,
      content: msg.content
    }));
    
    // 调用智能混合查询API（自动判断是查数据库还是知识库）
    const response = await fetch('/api/RagflowAI/chat/smart', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token') || ''}`
      },
      body: JSON.stringify({
        message: message,
        history: history
      })
    });
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }
    
    // 创建AI消息对象
    const aiMessage = {
      role: 'assistant',
      content: '',
      timestamp: new Date()
    };
    messages.value.push(aiMessage);
    
    // 智能混合查询返回JSON响应（不是流式）
    const result = await response.json();
    console.log('🎯 智能查询结果:', result);
    console.log('🔍 result.data:', JSON.stringify(result.data, null, 2));
    console.log('🔍 result.data.databaseResult:', result.data?.databaseResult);
    console.log('🔍 result.data.queryType:', result.data?.queryType);
    
    // 检查返回状态（兼容 status=true 或 200 的两种风格）
    const ok = result?.status === 200 || result?.status === true || result?.code === 200 || result?.success === true;
    if (!ok) {
      aiMessage.content = `❌ ${result.message || '查询失败'}`;
    } else {
      const data = result.data;
      console.log('✅ 进入数据处理, queryType:', data.queryType);
      
      // 构建回复内容
      let content = '';
      
      // 显示查询类型标识
      console.log('🔍 data.queryType === "Database"?', data.queryType === 'Database');
      if (data.queryType === 'Database') {
        console.log('✅ 进入 Database 分支');
        content += '📊 **[实时数据查询]**\n\n';
        
        // 显示数据库查询结果
        console.log('🔍 data.databaseResult?', !!data.databaseResult);
        console.log('🔍 data.databaseResult.data?', !!data.databaseResult?.data);
        if (data.databaseResult && data.databaseResult.data) {
          console.log('✅ 进入 databaseResult.data 分支');
          const dbData = data.databaseResult.data;
          
          content += `**${data.databaseResult.description}**\n\n`;
          
          // 如果有数据，显示为表格
          console.log('🔍 Array.isArray(dbData)?', Array.isArray(dbData));
          console.log('🔍 dbData.length?', dbData.length);
          if (Array.isArray(dbData) && dbData.length > 0) {
            console.log('✅ 开始生成表格, 数据条数:', dbData.length);
            // 获取第一行数据的所有键作为表头
            const firstItem = dbData[0];
            const keys = Object.keys(firstItem);
            
            // 创建表格 (不使用 \n，因为 formatMessage 会把它转成 <br> 破坏 HTML)
            content += '<table class="data-table">';
            
            // 表头
            content += '<thead><tr>';
            keys.forEach(key => {
              content += `<th>${key}</th>`;
            });
            content += '</tr></thead>';
            
            // 表体 (限制显示前50条)
            content += '<tbody>';
            const displayData = dbData.slice(0, 50);
            displayData.forEach(item => {
              content += '<tr>';
              keys.forEach(key => {
                const value = item[key];
                // 格式化日期
                if (value && typeof value === 'string' && value.match(/^\d{4}-\d{2}-\d{2}/)) {
                  content += `<td>${value.substring(0, 19).replace('T', ' ')}</td>`;
                } else {
                  content += `<td>${value !== null && value !== undefined ? value : ''}</td>`;
                }
              });
              content += '</tr>';
            });
            content += '</tbody>';
            content += '</table>';
            console.log('✅ 表格生成完成');
            
            if (dbData.length > 50) {
              content += `<br><em>注: 仅显示前50条，共${dbData.length}条数据</em>`;
            }
          } else {
            console.log('❌ dbData 不是数组或长度为0');
            content += '未查询到数据';
          }
        } else {
          console.log('❌ databaseResult 或 databaseResult.data 不存在');
          content += data.answer || '查询成功，但没有返回数据';
        }
        
      } else if (data.queryType === 'KnowledgeBase') {
        console.log('✅ 进入 KnowledgeBase 分支');
        content += '📚 **[知识库查询]**\n\n';
        content += data.answer || '抱歉，没有找到相关信息。';
      } else if (data.queryType === 'Hybrid') {
        console.log('✅ 进入 Hybrid 分支');
        content += '🔄 **[智能混合查询]**\n\n';
        content += data.answer || '抱歉，没有找到相关信息。';
      } else {
        console.log('⚠️ 未识别的查询类型:', data.queryType);
        // 未识别类型，显示原始答案
        content += data.answer || '抱歉，没有找到相关信息。';
      }
      
      // 显示执行时间
      if (data.executionTimeMs) {
        content += `\n\n⏱️ *查询耗时: ${data.executionTimeMs}ms*`;
      }
      
      console.log('🎯 最终生成的 content 长度:', content.length);
      console.log('🎯 最终生成的 content 前200字符:', content.substring(0, 200));
      aiMessage.content = content;
    }
    
    nextTick(() => scrollToBottom());
    
  } catch (error) {
    console.error('发送消息失败:', error);
    messages.value.push({
      role: 'assistant',
      content: `抱歉，发生了错误：${error.message}`,
      timestamp: new Date()
    });
    proxy.$message.error('发送失败: ' + error.message);
  } finally {
    isLoading.value = false;
    nextTick(() => scrollToBottom());
  }
};

const askQuestion = (question) => {
  inputMessage.value = question;
  sendMessage();
};

const handleEnter = (e) => {
  if (e.shiftKey) return;
  e.preventDefault();
  sendMessage();
};

const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
  }
};

// 根据内容添加类型样式（数据库/知识库/混合）
const detectMessageTypeClass = (content) => {
  if (!content || typeof content !== 'string') return '';
  if (content.includes('[实时数据查询]')) return 'type-db';
  if (content.includes('[知识库查询]')) return 'type-kb';
  if (content.includes('[智能混合查询]')) return 'type-hybrid';
  return '';
};

const formatMessage = (content) => {
  if (!content) return '';
  return content
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.*?)\*/g, '<em>$1</em>')
    .replace(/`(.*?)`/g, '<code>$1</code>')
    .replace(/\n/g, '<br>');
};

const formatTime = (timestamp) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  const now = new Date();
  const diff = now - date;
  if (diff < 60000) return '刚刚';
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`;
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`;
  return date.toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' });
};

const handleResize = () => {
  const maxX = window.innerWidth - (isOpen.value ? 400 : 60);
  const maxY = window.innerHeight - (isOpen.value ? 600 : 60);
  position.x = Math.min(position.x, maxX);
  position.y = Math.min(position.y, maxY);
};

// 检测后端连接状态
const checkConnection = async () => {
  try {
    const response = await fetch('/api/RagflowAI/health', {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token') || ''}`
      }
    });
    const result = await response.json();
    isConnected.value = result.status === 'healthy';
    console.log('🤖 AI服务状态:', result);
  } catch (error) {
    console.warn('⚠️ AI服务连接失败:', error);
    isConnected.value = false;
  }
};

onMounted(() => {
  window.addEventListener('resize', handleResize);
  console.log('🤖 AI客服组件已加载');
  
  // 检测后端连接
  checkConnection();
  
  // 每30秒检测一次连接状态
  const intervalId = setInterval(checkConnection, 30000);
  
  // 保存interval ID以便清理
  window._aiChatInterval = intervalId;
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  stopDrag();
  
  // 清理定时器
  if (window._aiChatInterval) {
    clearInterval(window._aiChatInterval);
  }
});

defineExpose({ openChat, closeChat });
</script>

<style scoped lang="less">
.ai-chat-button {
  position: fixed;
  width: 64px;
  height: 64px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.5), 0 0 0 0 rgba(102, 126, 234, 0.4);
  cursor: move;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  transition: all 0.3s ease;
  animation: pulse 2s infinite;
  
  &:hover { 
    transform: scale(1.1) rotate(5deg);
    box-shadow: 0 12px 32px rgba(102, 126, 234, 0.6), 0 0 0 8px rgba(102, 126, 234, 0.1);
  }
  
  &:active {
    transform: scale(0.95);
  }
  
  .chat-icon { 
    width: 36px;
    height: 36px;
    svg {
      width: 100%;
      height: 100%;
      filter: drop-shadow(0 2px 4px rgba(0,0,0,0.2));
    }
  }
  
  .chat-badge {
    position: absolute;
    top: -2px;
    right: -2px;
    background: linear-gradient(135deg, #ff6b6b 0%, #ee5a6f 100%);
    color: white;
    border-radius: 12px;
    padding: 3px 7px;
    font-size: 11px;
    font-weight: bold;
    min-width: 20px;
    text-align: center;
    box-shadow: 0 2px 8px rgba(238, 90, 111, 0.4);
    animation: bounce 1s infinite;
  }
  
}

@keyframes pulse {
  0%, 100% {
    box-shadow: 0 8px 24px rgba(102, 126, 234, 0.5), 0 0 0 0 rgba(102, 126, 234, 0.4);
  }
  50% {
    box-shadow: 0 8px 24px rgba(102, 126, 234, 0.5), 0 0 0 8px rgba(102, 126, 234, 0.1);
  }
}

@keyframes bounce {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-4px); }
}


.ai-chat-window {
  position: fixed;
  width: 400px;
  height: 600px;
  background: radial-gradient(100% 100% at 0% 0%, rgba(255,255,255,0.95) 0%, rgba(255,255,255,0.98) 100%);
  border-radius: 16px;
  border: 1px solid rgba(102,126,234,0.15);
  box-shadow: 0 12px 48px rgba(18, 38, 63, 0.18);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  z-index: 9999;
  backdrop-filter: saturate(1.2) blur(6px);
}

.chat-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 14px 18px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: move;
  border-radius: 16px 16px 0 0;
  .header-title {
    display: flex;
    gap: 10px;
    align-items: center;
    .avatar-3d {
      width: 32px;
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgba(255, 255, 255, 0.25);
      border-radius: 50%;
      padding: 2px;
      svg {
        width: 100%;
        height: 100%;
        filter: drop-shadow(0 2px 4px rgba(0,0,0,0.15));
      }
    }
    .status-indicator {
      font-size: 12px;
      padding: 2px 10px;
      border-radius: 999px;
      background: rgba(255, 255, 255, 0.25);
      display: inline-flex;
      align-items: center;
      gap: 6px;
      &::before {
        content: '';
        display: inline-block;
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background: #ffb84d;
        box-shadow: 0 0 0 2px rgba(255,255,255,0.35) inset;
      }
      &.online {
        background: rgba(103, 194, 58, 0.28);
      }
      &.offline {
        background: rgba(255, 255, 255, 0.18);
      }
    }
    .title-text { font-weight: 600; letter-spacing: 0.3px; }
  }
  .header-actions {
    display: flex;
    gap: 5px;
    .action-btn {
      width: 28px;
      height: 28px;
      border: none;
      background: rgba(255, 255, 255, 0.22);
      color: white;
      border-radius: 6px;
      cursor: pointer;
      font-size: 16px;
      transition: all .2s ease;
      &:hover { background: rgba(255, 255, 255, 0.32); transform: translateY(-1px); }
    }
  }
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #f5f7fa;
}

.welcome-message {
  text-align: center;
  padding: 40px 20px;
  .welcome-icon { font-size: 48px; margin-bottom: 20px; }
  h3 { color: #303133; margin-bottom: 10px; }
  p { color: #909399; margin-bottom: 30px; }
  .quick-questions {
    display: flex;
    flex-direction: column;
    gap: 10px;
    .quick-btn {
      padding: 12px 20px;
      background: white;
      border: 1px solid #dcdfe6;
      border-radius: 8px;
      cursor: pointer;
      &:hover { border-color: #667eea; color: #667eea; }
    }
  }
}

.message-item {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  &.user {
    flex-direction: row-reverse;
    .message-content { align-items: flex-end; }
    .message-text {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
    }
  }
  .message-avatar {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    background: linear-gradient(135deg, #e6e9f0 0%, #eef1f5 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    box-shadow: 0 2px 6px rgba(0,0,0,0.08);
    overflow: hidden;
    
    .bear-avatar {
      width: 100%;
      height: 100%;
      display: block;
    }
  }
  .message-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 5px;
    max-width: 70%;
    .message-text {
      padding: 12px 16px;
      border-radius: 12px;
      background: white;
      color: #000000;
      line-height: 1.6;
      word-wrap: break-word;
      max-height: 400px;
      overflow-y: auto;
      box-shadow: 0 2px 8px rgba(0,0,0,0.06);
      
      &::-webkit-scrollbar {
        width: 6px;
      }
      
      &::-webkit-scrollbar-thumb {
        background: #c0c4cc;
        border-radius: 3px;
        
        &:hover {
          background: #a8abb2;
        }
      }
      
      &::-webkit-scrollbar-track {
        background: #f5f7fa;
        border-radius: 3px;
      }
    }
    .message-time {
      font-size: 12px;
      color: #909399;
      padding: 0 5px;
    }
  }
}

// 不同查询类型的高亮样式
.message-item.type-db .message-text {
  background: linear-gradient(180deg, #f0fff5 0%, #ffffff 60%);
  border-left: 4px solid #2ecc71;
}

.message-item.type-kb .message-text {
  background: linear-gradient(180deg, #f5f7ff 0%, #ffffff 60%);
  border-left: 4px solid #667eea;
}

.message-item.type-hybrid .message-text {
  background: linear-gradient(180deg, #f0fbff 0%, #ffffff 60%);
  border-left: 4px solid #00c2ff;
}

.typing-indicator {
  display: flex;
  gap: 5px;
  padding: 12px 16px;
  background: white;
  border-radius: 12px;
  span {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: #909399;
    animation: typing 1.4s infinite;
    &:nth-child(2) { animation-delay: 0.2s; }
    &:nth-child(3) { animation-delay: 0.4s; }
  }
}

@keyframes typing {
  0%, 60%, 100% { opacity: 0.3; transform: translateY(0); }
  30% { opacity: 1; transform: translateY(-10px); }
}

// 数据表格样式
:deep(.data-table) {
  width: 100%;
  border-collapse: collapse;
  margin: 10px 0;
  font-size: 12px;
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  
  thead {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    
    th {
      padding: 12px 8px;
      text-align: left;
      font-weight: 600;
      white-space: nowrap;
      border-right: 1px solid rgba(255, 255, 255, 0.2);
      
      &:last-child {
        border-right: none;
      }
    }
  }
  
  tbody {
    tr {
      transition: background-color 0.2s;
      border-bottom: 1px solid #f0f0f0;
      
      &:hover {
        background-color: #f5f7fa;
      }
      
      &:last-child {
        border-bottom: none;
      }
      
      td {
        padding: 10px 8px;
        border-right: 1px solid #f0f0f0;
        max-width: 200px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        
        &:last-child {
          border-right: none;
        }
      }
    }
    
    // 斑马纹
    tr:nth-child(even) {
      background-color: #fafafa;
      
      &:hover {
        background-color: #f5f7fa;
      }
    }
  }
}

.chat-input {
  padding: 15px 20px;
  background: white;
  border-top: 1px solid #e4e7ed;
  display: flex;
  gap: 10px;
  align-items: flex-end;
  border-radius: 0 0 12px 12px;
  .send-btn {
    width: 40px;
    height: 40px;
    border: none;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 8px;
    cursor: pointer;
    font-size: 20px;
    &:disabled { opacity: 0.5; cursor: not-allowed; }
  }
}
</style>

